//
//  GYModifyPasswordViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/16.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYModifyPasswordViewController.h"
#import "GYNetWorkTools.h"
#import "GYUser.h"

@interface GYModifyPasswordViewController ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (strong, nonatomic) IBOutlet UITextField *codeTF;

@property (weak, nonatomic) IBOutlet UITextField *pwNewTF;
@property (weak, nonatomic) IBOutlet UITextField *conTF;
@property (weak, nonatomic) IBOutlet UIButton *conBtu;
@property (weak, nonatomic) IBOutlet UIButton *SMSBtu;

/** 定时器 */
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation GYModifyPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.conBtu.layer.cornerRadius = 4;
    self.SMSBtu.layer.cornerRadius = 4;
    self.navigationItem.title = @"修改登陆密码";
    
}
- (IBAction)getSMSCode:(UIButton *)sender {
    if ([self isMobileNumber:self.phoneTF.text]) {
        [GYNetWorkTools requestUserModifyPasswordSMSCode:self.phoneTF.text success:^(NSDictionary *obj) {
            //NSLog(@"obj ===== %@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                [self.codeTF becomeFirstResponder];
                NSLog(@"短信验证码已发出....");
                //2.1.创建GCD定时器
                NSDictionary *datas = [obj objectForKey:@"datas"];
                __block int count = [[datas objectForKey:@"sms_time"] intValue];
                sender.enabled = NO;
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
                
                self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
                dispatch_source_set_event_handler(self.timer, ^{
                    //2.2改变按钮文字
                    count = count - 1;
                    if (count <= 0) {
                        self.timer = nil;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                            sender.enabled = YES;
                        });
                    }else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setTitle:[NSString stringWithFormat:@"%d秒",count] forState:UIControlStateNormal];
                        });
                    }
                });
                dispatch_resume(self.timer);
                
            }else {
                NSLog(@"短信验证码发送失败...");
            }
        } error:^(NSError *error) {
            NSLog(@"loadUserModifyPasswordSMSCodeFailed===%@",error);
        }];
    }else {
        NSLog(@"请输入正确的手机号...");
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)conBtuClick:(UIButton *)sender {
    
    if (![self isMobileNumber:self.phoneTF.text]) {
        NSLog(@"请输入正确的手机号...");
    }
    
    if (self.codeTF.text.length == 0) {
        NSLog(@"请输入验证码...");
        return;
    }
    
    NSString *pwd = self.pwNewTF.text;
    if (![self judgePassWordLegal:pwd]) {
        NSLog(@"密码为6-16的数字和字母组成");
        return;
    }
    
    if (![self.conTF.text isEqualToString:pwd]) {
        NSLog(@"输入密码与确认密码不一致...");
        return;
    }
    

    //提交修改密码的功能
    [GYNetWorkTools requestUserModifyPassword:self.phoneTF.text captcha:self.codeTF.text password:self.pwNewTF.text success:^(NSDictionary *obj) {
        //NSLog(@"obj ===== %@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyTextView showSuccessText:@"修改密码成功!"];
            //保存用户信息
            GYUser *user = [[GYUser alloc] initWithDic:datas];
            [user saveUserInfo];
            
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            NSLog(@"网络加载出错...");
            [EasyTextView showText:@"修改密码失败!"];
        }
    } error:^(NSError *error) {
        [EasyTextView showText:@"修改密码失败!"];
        NSLog(@"laodUserModifyPasswordFailed===%@",error);
    }];
}

/*  
 判断用户输入的密码是否符合规范，符合规范的密码要求：
1. 长度大于6位
2. 密码中必须同时包含数字和字母
*/
- (BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

#pragma mark--判断手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    //     NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CM = @" ^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    //     NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CU =  @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    //     NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    NSString * CT = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
